<?php
/**
 * Works with translations
 */
class Translation extends Zend_Db_Table
{
	/**
	 * Database table name
	 * 
	 * @var string
	 */
	protected $_name       = 'translation';
	
	/**
	 * Database primary column
	 * 
	 * @var string
	 */
	protected $_primaryKey = 'id';
	
	/**
	 * Users
	 *  
	 */
	private $User = null;
	
	/**
	 * Read user session domain
	 */
	public function init()
	{
		$this->User = Wise_User_Session::getInstance();
	}

	/**
	 * Search for the terms
	 * 
	 * @param string $searchPhrase search phrase
	 * @param int $sourceLangId language database id
	 */
	public function getMatchedTerms($searchPhrase, $sourceLangId)
	{
		$condition = $this->select();

		$condition->from('translation', 
			array('relevance' => new Zend_Db_Expr('MATCH (title) AGAINST ("'.$searchPhrase.'")')
				, 'term_id'
				, 'title')
			)
				  ->where('MATCH (title) AGAINST (?)', $searchPhrase)
				  ->where('lang_id = ?', $sourceLangId)
				  ->order('relevance DESC')
				  ->limit(15)
				  ;

		return $this->fetchAll($condition); 
	}

	/**
	 * Search for phrase
	 */
	public function searchTermsTranslation($searchPhrase)
	{
		// Get languages from Request
    	$targetLangId = $this->User->target_lang;
    	$sourceLangId = $this->User->source_lang;
    	
		$matchedTerms = $this->getMatchedTerms($searchPhrase, $sourceLangId);
		
		// Build translations list for matched terms
		$termTranslation = array();
		
		// Get terms translations for target languge
		foreach ($matchedTerms as $term) {
			$condition = $this->select();
			$condition->where('lang_id = ?', $targetLangId);
			$condition->where('term_id = ?', $term->term_id);
			$translated_term = $this->fetchRow($condition);
			
			if (null !== $translated_term) {
				$termTranslation[] = array(
					  'target_title' => $translated_term->title
					, 'source_title' => $term->title
				);
			}
		}
		
		return $termTranslation;
	}

}